package com.woniuxy.cloud.carl.marketing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.cloud.carl.marketing.client.param.AddFullDiscount;
import com.woniuxy.cloud.carl.marketing.client.param.GetCouponParam;
import com.woniuxy.cloud.carl.marketing.common.StatusEnum;
import com.woniuxy.cloud.carl.marketing.infra.model.*;
import com.woniuxy.cloud.carl.marketing.infra.mapper.FullDiscountCouponMapper;
import com.woniuxy.cloud.carl.marketing.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.exceptions.MallException;
import com.woniuxy.result.CommonResultCodeEnum;
import com.woniuxy.result.Result;
import com.woniuxy.utils.Assert;
import org.redisson.Redisson;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RSortedSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 满减券 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2023-07-19
 */
@Service
public class FullDiscountCouponServiceImpl extends ServiceImpl<FullDiscountCouponMapper, FullDiscountCoupon> implements FullDiscountCouponService {
    @Autowired
    private CouponSpuService couponSpuService;
    @Autowired
    private StoreCouponService storeCouponService;
    @Autowired
    private ConditionCouponService conditionCouponService;
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public Result addFullDiscountCoupon(AddFullDiscount param) {
        FullDiscountCoupon fullDiscountCoupon = BeanUtil.copyProperties(param, FullDiscountCoupon.class);
        fullDiscountCoupon.setStatus(StatusEnum.COUPON_NORMAL.getCode());
        Snowflake snowflake = new Snowflake();
        String str = snowflake.nextIdStr();
        fullDiscountCoupon.setFullDiscountCouponId(str);
        fullDiscountCoupon.setTypeFlag(StatusEnum.FULL_DISCOUNT_FLAG.getCode());
        save(fullDiscountCoupon);
        ArrayList<ConditionCoupon> conditionCoupons = new ArrayList<>();
        param.getConditionIds().forEach(o->{
            ConditionCoupon conditionCoupon = new ConditionCoupon();
            conditionCoupon.setCouponId(str);
            conditionCoupon.setConditionId(o);
            conditionCoupons.add(conditionCoupon);
        });
        conditionCouponService.saveBatch(conditionCoupons);
        RScoredSortedSet<Object> scoredSortedSet = redissonClient.getScoredSortedSet("coupon_count");
        scoredSortedSet.add(param.getCount(),str);
        return Result.success(CommonResultCodeEnum.SUCCESS,"新增优惠券成功",null);
    }

//    @Override
//    public Result delCoupon(String couponId) {
//        removeById(couponId);
//        conditionCouponService.remove(new QueryWrapper<ConditionCoupon>().eq("coupon_id",couponId));
//        couponSpuService.remove(new QueryWrapper<CouponSpu>().eq("coupon_id",couponId));
//        storeCouponService.remove(new QueryWrapper<StoreCoupon>().eq("coupon_id",couponId));
//        Coupon coupon = new Coupon();
//        coupon.setCouponStatus(StatusEnum.USER_COUPON_NOT_SHELVES.getCode());
//        couponService.update(coupon,new UpdateWrapper<Coupon>().
//                eq("coupon_id",couponId).eq("coupon_status",StatusEnum.USER_COUPON_NOT_USE.getCode()));
//        return Result.success();
//    }

    @Override
    public Result<Page<FullDiscountCoupon>> getCoupon(GetCouponParam param) {
        Page<FullDiscountCoupon> page = new Page<>(param.getPageNum(), param.getPageSize());
        if (param.getCouponId()!=null&&!param.getCouponId().equals("")){
            IPage<FullDiscountCoupon> iPage = page(page, new QueryWrapper<FullDiscountCoupon>().
                    eq("full_discount_coupon_id", param.getCouponId()));
            Page<Deduction> page1 = BeanUtil.copyProperties(iPage, Page.class);
            return Result.success(page1);
        }else {
            ArrayList<String> strings = new ArrayList<>();
            boolean b=false;
            if (param.getConditionId()!=null||param.getStoreId()!=null||param.getSpuId()!=null){
                if (param.getConditionId()!=null) {
                    List<ConditionCoupon> conditionCouponList = conditionCouponService.list(new QueryWrapper<ConditionCoupon>()
                            .eq("condition_id", param.getConditionId()));
                    conditionCouponList.forEach(o->strings.add(o.getCouponId()));
                }
                if (param.getStoreId()!=null){
                    List<StoreCoupon> storeCouponList = storeCouponService.list(new QueryWrapper<StoreCoupon>()
                            .eq("store_id", param.getStoreId()));
                    if (strings==null) storeCouponList.forEach(o->strings.add(o.getCouponId()));
                    else {
                        ArrayList<String> list = new ArrayList<>();
                        storeCouponList.forEach(o->list.add(o.getCouponId()));
                        strings.retainAll(list);
                    }
                }
                if (param.getSpuId()!=null){
                    List<CouponSpu> couponSpuList = couponSpuService.list(new QueryWrapper<CouponSpu>()
                            .eq("spu_id", param.getSpuId()));
                    if (strings==null) couponSpuList.forEach(o->strings.add(o.getCouponId()));
                    else {
                        ArrayList<String> list = new ArrayList<>();
                        couponSpuList.forEach(o->list.add(o.getCouponId()));
                        strings.retainAll(list);
                    }

                }
                b=true;
            }
            if (strings.size()==0&b) return Result.fail(CommonResultCodeEnum.DATA_NOT_FOUND,"查询结果为空");
            QueryWrapper<FullDiscountCoupon> wrapper = new QueryWrapper<FullDiscountCoupon>();
            if (strings.size()!=0)
            wrapper.in("coupon_id",strings);
            IPage<FullDiscountCoupon> iPage = page(page, wrapper);
            List<FullDiscountCoupon> list = iPage.getRecords();
            if (param.getBuffFlag()!=null) list=list.stream().filter(o->o.getBuffFlag()== param.getBuffFlag()).collect(Collectors.toList());
            if (param.getStatus()!=null) list=list.stream().filter(o->o.getStatus()== param.getStatus()).collect(Collectors.toList());
            iPage.setRecords(list);
            Page<Deduction> page1 = BeanUtil.copyProperties(iPage, Page.class);
            return Result.success(page1);
        }
    }

    @Override
    public Result<FullDiscountCoupon> useFullDiscount(BigDecimal price, String couponId) {
        FullDiscountCoupon discountCoupon = getById(couponId);
        Assert.state(discountCoupon!=null,"优惠券信息错误");
        if (price.compareTo(discountCoupon.getTargetAmount())<0)
            throw new MallException(CommonResultCodeEnum.ILLEGAL_STATE,"订单金额不足，无法使用");
        return Result.success(discountCoupon);
    }


}
